package flc.ast.fragment;

import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import flc.ast.AppConfig;
import flc.ast.R;
import flc.ast.activity.LikeActivity;
import flc.ast.activity.ListActivity;
import flc.ast.activity.RankActivity;
import flc.ast.activity.ReadRecordActivity;
import flc.ast.activity.RecommendActivity;
import flc.ast.activity.SearchActivity;
import flc.ast.adapter.LikeAdapter;
import flc.ast.adapter.MovieKindAdapter;
import flc.ast.adapter.MyBannerAdapter;
import flc.ast.adapter.RecommendAdapter;
import flc.ast.bean.RecordBean;
import flc.ast.databinding.FragmentHomeBinding;
import flc.ast.utils.AppSpUtils;
import stark.common.api.StkResApi;
import stark.common.base.IReqRetCallback;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.base.BaseWebviewActivity;
import stark.common.basic.event.EventStatProxy;
import stark.common.bean.StkResBean;
import stark.common.bean.StkTagResBean;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> {

    private MovieKindAdapter movieKindAdapter;
    private int oldPosition = 0;
    private RecommendAdapter recommendAdapter;
    private LikeAdapter likeAdapter;


    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);
        mDataBinding.ivRecord.setOnClickListener(this);
        mDataBinding.ivHot.setOnClickListener(this);
        mDataBinding.ivLatest.setOnClickListener(this);
        mDataBinding.ivClassic.setOnClickListener(this);
        mDataBinding.ivType1.setOnClickListener(this);
        mDataBinding.ivType2.setOnClickListener(this);
        mDataBinding.ivType3.setOnClickListener(this);
        mDataBinding.ivType4.setOnClickListener(this);
        mDataBinding.ivType5.setOnClickListener(this);
        mDataBinding.ivType6.setOnClickListener(this);
        mDataBinding.tvRecommendMore.setOnClickListener(this);
        mDataBinding.tvLikeMore.setOnClickListener(this);
        mDataBinding.tvTypeMore.setOnClickListener(this);
        //banner
        mDataBinding.movieBanner.setBannerGalleryEffect(30, 10);//40两边露出距离，20图片之间距离
        mDataBinding.movieBanner.isAutoLoop(true);//false不自动轮播
        mDataBinding.movieBanner.setIndicator(new CircleIndicator(getActivity()));
        mDataBinding.movieBanner.setIndicatorGravity(IndicatorConfig.Direction.CENTER);
        mDataBinding.rvMovieKindList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        movieKindAdapter = new MovieKindAdapter();
        mDataBinding.rvMovieKindList.setAdapter(movieKindAdapter);
        movieKindAdapter.setOnItemClickListener(this);
        //精彩推荐
        mDataBinding.rvRecommendList.setLayoutManager(new GridLayoutManager(mContext, 2));
        recommendAdapter = new RecommendAdapter();
        mDataBinding.rvRecommendList.setAdapter(recommendAdapter);
        recommendAdapter.setOnItemClickListener(this);
        //猜你喜欢
        mDataBinding.rvLikeList.setLayoutManager(new GridLayoutManager(mContext, 3));
        likeAdapter = new LikeAdapter();
        mDataBinding.rvLikeList.setAdapter(likeAdapter);
        likeAdapter.setOnItemClickListener(this);
        //搜索
        mDataBinding.ivMovieSearch.setOnClickListener(this);
        mDataBinding.etMovieKey.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String movieKey = mDataBinding.etMovieKey.getText().toString().trim();
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (movieKey.isEmpty()) {
                        ToastUtils.showShort(getString(R.string.please_input_search));
                        return true;
                    }
                    SearchActivity.movieKey = movieKey;
                    startActivity(SearchActivity.class);
                }
                return false;
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivMovieSearch://搜素
                String movieKey = mDataBinding.etMovieKey.getText().toString().trim();
                if (movieKey.isEmpty()) {
                    ToastUtils.showShort(getString(R.string.please_input_search));
                    return;
                }
                SearchActivity.movieKey = movieKey;
                startActivity(SearchActivity.class);
                break;
            case R.id.ivRecord://浏览记录
                startActivity(ReadRecordActivity.class);
                break;
            case R.id.ivHot://最热
                ListActivity.type=0;
                startActivity(ListActivity.class);
                break;
            case R.id.ivLatest://最新
                ListActivity.type=1;
                startActivity(ListActivity.class);
                break;
            case R.id.ivClassic://高分
                ListActivity.type=2;
                startActivity(ListActivity.class);
                break;
            //分类排行
            case R.id.tvTypeMore:
            case R.id.ivType1:
                RankActivity.selPosition=0;
                startActivity(RankActivity.class);
                break;
            case R.id.ivType2:
                RankActivity.selPosition=1;
                startActivity(RankActivity.class);
                break;
            case R.id.ivType3:
                RankActivity.selPosition=2;
                startActivity(RankActivity.class);
                break;
            case R.id.ivType4:
                RankActivity.selPosition=3;
                startActivity(RankActivity.class);
                break;
            case R.id.ivType5:
                RankActivity.selPosition=4;
                startActivity(RankActivity.class);
                break;
            case R.id.ivType6:
                RankActivity.selPosition=5;
                startActivity(RankActivity.class);
                break;
            case R.id.tvRecommendMore://精彩推荐
                startActivity(RecommendActivity.class);
                break;
            case R.id.tvLikeMore://猜你喜欢
                startActivity(LikeActivity.class);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == movieKindAdapter) {
            movieKindAdapter.getItem(oldPosition).setSelected(false);
            movieKindAdapter.notifyItemChanged(oldPosition);
            oldPosition = position;
            movieKindAdapter.getItem(position).setSelected(true);
            movieKindAdapter.notifyItemChanged(position);
            List<StkResBean> listBanner = new ArrayList<>();
            for (StkResBean stkResBean : movieKindAdapter.getItem(position).getDataList()) {
                listBanner.add(stkResBean);
            }
            MyBannerAdapter myMovieBannerAdapter = new MyBannerAdapter(listBanner, mContext);
            mDataBinding.movieBanner.setAdapter(myMovieBannerAdapter, true);//false不无限循环
            mDataBinding.movieBanner.setIndicatorSelectedColor(Color.parseColor("#0A61E8"));
            mDataBinding.movieBanner.setIndicatorNormalColor(Color.parseColor("#616F8C"));
            mDataBinding.movieBanner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(Object data, int position) {
                    StkResBean bean= (StkResBean) mDataBinding.movieBanner.getAdapter().getData(position);
                    saveRecord(bean);
                    BaseWebviewActivity.open(mContext, bean.getUrl(), bean.getName());
                }
            });
        } else {
            StkResBean bean = (StkResBean) adapter.getItem(position);
            saveRecord(bean);
            BaseWebviewActivity.open(mContext, bean.getUrl(), bean.getName());
        }
    }

    @Override
    protected void initData() {
        getBannerData();
        getRecommendData();
        getLikeData();
    }

    private void getBannerData() {
        StkResApi.getChildTagAndResource(this, AppConfig.BANNER_DATA, StkResApi.createParamMap(0, 10), false, new IReqRetCallback<List<StkTagResBean>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<StkTagResBean> result) {
                if (success) {
                    if (result != null && result.size() > 0) {
                        movieKindAdapter.setList(result);
                        movieKindAdapter.getItem(0).setSelected(true);
                        movieKindAdapter.notifyItemChanged(0);
                        List<StkResBean> listBanner = new ArrayList<>();
                        for (StkResBean stkResBean : movieKindAdapter.getItem(0).getDataList()) {
                            listBanner.add(stkResBean);
                        }
                        MyBannerAdapter myMovieBannerAdapter = new MyBannerAdapter(listBanner, mContext);
                        mDataBinding.movieBanner.setAdapter(myMovieBannerAdapter, true);//false不无限循环
                        mDataBinding.movieBanner.setIndicatorSelectedColor(Color.parseColor("#0A61E8"));
                        mDataBinding.movieBanner.setIndicatorNormalColor(Color.parseColor("#616F8C"));
                        mDataBinding.movieBanner.setOnBannerListener(new OnBannerListener() {
                            @Override
                            public void OnBannerClick(Object data, int position) {
                                StkResBean bean= (StkResBean) mDataBinding.movieBanner.getAdapter().getData(position);
                                saveRecord(bean);
                                BaseWebviewActivity.open(mContext, bean.getUrl(), bean.getName());
                            }
                        });
                    }
                }
            }
        });
    }

    private void getRecommendData() {
        StkResApi.getTagResourceList(this, AppConfig.RECOMMEND_DATA, StkResApi.createParamMap(0, 4), false, new IReqRetCallback<List<StkResBean>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<StkResBean> result) {
                if (success) {
                    if (result != null && result.size() > 0) {
                        recommendAdapter.setList(result);
                    }
                }
            }
        });
    }

    private void getLikeData() {
        StkResApi.getTagResourceList(this, AppConfig.LIKE_DATA, StkResApi.createParamMap(0, 6), false, new IReqRetCallback<List<StkResBean>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<StkResBean> result) {
                if (success) {
                    if (result != null && result.size() > 0) {
                        likeAdapter.setList(result);
                    }
                }
            }
        });
    }

    private void saveRecord(StkResBean bean) {
        List<StkResBean> listSave = new ArrayList<>();
        listSave.add(bean);
        List<StkResBean> listSp = AppSpUtils.getReadRecordList();
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            AppSpUtils.saveReadRecordList(listSp);
        } else {
            AppSpUtils.saveReadRecordList(listSave);
        }
    }

}